package com.distributor;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ActivityLogin extends Activity 
{
	Button btnSubmit,clear;
	private EditText etpassword;
	
	HttpConn httpConn=new HttpConn();
	private ProgressDialog pd=null;
	
	private Handler handler=new Handler();
	TelephonyManager telephonyManager;
	
	Runnable getLogin;
	String userId,passwd,CheckSum,url,result;
	UserInfo userInfo;
	ImageView imeiDialog;
	MD5Generator md5Generator=new MD5Generator();
	
	@Override
	public void onBackPressed() 
	{
		// TODO Auto-generated method stub
		
		new AlertDialog.Builder(ActivityLogin.this)
        .setTitle( "Exit Application." )
        .setMessage( "Are you sure you want to Exit ?" )
        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface arg0, int arg1) 
            {
                //do stuff onclick of YES
            	finish();
            }

			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				
			}
        })
        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
         {
         	public void onClick(DialogInterface arg0, int arg1)
            {
                //do stuff onclick of CANCEL
            	arg0.dismiss();
            }

			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
			}
			
        }).show();
	} 
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        telephonyManager = (TelephonyManager)getSystemService(this.TELEPHONY_SERVICE);
        //AppData.imei=telephonyManager.getDeviceId();
        AppData.imei="359462044688728";
        //AppData.imei="351823051157469";
        imeiDialog=(ImageView)findViewById(R.id.imei);
    
        
        btnSubmit=(Button)findViewById(R.id.btnSubmit);
        clear=(Button)findViewById(R.id.btnReeset); 
        
        etpassword=(EditText)findViewById(R.id.etPassword); 
        
        /*imeiDialog.setOnClickListener(new OnClickListener()
        {
			public void onClick(View arg0) 
			{
				// TODO Auto-generated method stub
				final AlertDialog.Builder alert = new AlertDialog.Builder(ActivityLogin.this);

				alert.setTitle("Enter IMEI");
				
				// Set an EditText view to get user input 
				final EditText input = new EditText(getApplicationContext());
				input.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
				alert.setView(input);
 
				alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
				{
					public void onClick(DialogInterface dialog, int whichButton) 
					{
						 
						if(input.getText().toString().trim().length()>0)
						{
							 AppData.imei=input.getText().toString();
						}
						else
						{
							Toast.makeText(ActivityLogin.this,"Invalid Input.",Toast.LENGTH_SHORT).show();
						 
						}
					}
				});

				alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
				{
				  public void onClick(DialogInterface dialog, int whichButton) 
				  {
					  dialog.dismiss();
				  }
				});

				alert.show(); 
			}
		});*/
         
        btnSubmit.setOnClickListener(new View.OnClickListener()
        { 
			public void onClick(final View arg0) 
			{
				// TODO Auto-generated method stub
 
				if(!etpassword.getText().toString().equals(""))
				{	
					//Toast.makeText(getApplicationContext(),"IMEI:"+AppData.imei ,Toast.LENGTH_SHORT).show();
					arg0.setBackgroundDrawable(getResources().getDrawable(R.drawable.go_active));
					pd =ProgressDialog.show(ActivityLogin.this,    
						    	null, "Please Wait..", true);
					pd.setContentView(R.layout.progress); 
					new Thread(getLogin).start();
					
				}
				else
				{
					Toast.makeText(getApplicationContext(),"Please Enter Password" ,Toast.LENGTH_SHORT).show();
				}
				
			}
			
		});
        
        clear.setOnClickListener(new OnClickListener() 
        {
			public void onClick(final View v) 
			{
				v.setBackgroundDrawable(getResources().getDrawable(R.drawable.cancel_active));
				new AlertDialog.Builder(ActivityLogin.this)
		        .setTitle("Exit Application")
		        .setMessage("Are you sure you want to Logout?")
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		                //do stuff onclick of YES
		            	setResult(2);
		            	finish();
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
						
					}
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	v.setBackgroundDrawable(getResources().getDrawable(R.drawable.cancel));
		            	arg0.dismiss();
		               
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show(); 
			}
		});
        
        getLogin=new Runnable()
        {
			
			public void run() 
			{

				try
				{
					userId=AppData.imei;
					passwd=md5Generator.MD5(etpassword.getText().toString());
					System.out.println("UserId:\n"+userId+"\nPassword:"+passwd); 
					MD5Generator generator=new MD5Generator();
					CheckSum=generator.MD5(generator.SHA1(userId+"|"+passwd));
					System.out.println("CheckSum==>"+CheckSum); 
					url=AppData.hostURL+"/WebService/iTopUp/distributorapp.php/MobileAuthentication/LoginUsername/"+userId+"/LoginPassword/"+passwd+"/Checksum/"+CheckSum+"/format/json";
					System.out.println("Final URL:==>"+url);
					System.out.println("");
					result=httpConn.createHttpConn(url);
					System.out.println("Result:"+result);
					if(result==null)
					{
						handler.post( new Runnable() 
						{ 
							public void run() 
							{
							 	pd.dismiss();
								btnSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.go)); 
								Toast.makeText(ActivityLogin.this,getString(R.string.conn_msg), Toast.LENGTH_SHORT).show();
							}
							
						});
						
					}
					else
					{
						 
						JSONObject jsonObject=new JSONObject(result); 
						String responseCode=jsonObject.getString("ResponseCode");
						final String responseDesc=jsonObject.getString("ResponseDescription");
						
						
						if(responseCode.equals("000")&& responseDesc.equals("Successfull"))
						{
							final UserInfo userInfo=new UserInfo();
							userInfo.setLoginID(jsonObject.getString("LoginId"));
							userInfo.setPublickey(jsonObject.getString("PublicKey"));
							userInfo.setTransactionPassword((jsonObject.getString("TransactionPassword")));
							userInfo.setPasswordSet(jsonObject.getString("PasswordSet"));
							userInfo.setResellerLevel(Integer.parseInt(jsonObject.getString("ResellerLevel")));
							userInfo.setMaxLevel(Integer.parseInt(jsonObject.getString("MaxLevel")));
							userInfo.setLoginPin(passwd); 
//							userInfo.setResellerLevel(1);
//							userInfo.setMaxLevel(4);
							if(jsonObject.has("AccountType"))
								userInfo.setAccountType(jsonObject.getString("AccountType"));
//							else
//								userInfo.setAccountType("s");

							
							System.out.println("Login ID:"+userInfo.getLoginID()+
												"\nPublic key:"+userInfo.getpublickey()+
												"\nTransactioon Paqssword:"+userInfo.getTransactionPassword()+
												"\nReseller Level:"+userInfo.getResellerLevel()+
												"\nMax Level:"+userInfo.getMaxLevel()+
												"\nAccount Type:"+userInfo.getAccountType()+
												"\nlogin PIn:"+passwd);
												 
							
							AppData.setUserInfo(userInfo);
							
							handler.post(new Runnable() 
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(ActivityLogin.this,"Login successful" ,Toast.LENGTH_SHORT).show();
									if(userInfo.getPasswordSet().equals("0"))
									{
										new ChangeCredentialsDialog(ActivityLogin.this).show();
									}
									else
									{
										startActivity(new Intent(ActivityLogin.this,TabMain.class));
										finish();
									}
								}
							});
							
//							startActivity(new Intent(Login.this,ButtonPayActivity.class));
//							finish();
							
						}
						else
						{
							handler.post(new Runnable() 
							{
								public void run() 
								{
									pd.dismiss();
									btnSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.go));
									Toast.makeText(ActivityLogin.this,responseDesc, Toast.LENGTH_SHORT).show();
									etpassword.setText("");
							 	}	
							});
							
						}
						 
						
					} 
					
				}
				catch(final Exception e)
				{
					
					handler.post(new Runnable() 
					{
						public void run() 
						{
							pd.dismiss();
							btnSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.go));
							Toast.makeText(ActivityLogin.this,e.toString()+"\n"+e.getMessage(), Toast.LENGTH_SHORT).show();
					 	}	
					});
					
				}
			}
		};
    }
    
    private class ChangeCredentialsDialog extends Dialog implements OnClickListener 
	 {
		 
	 	EditText etCurrentPassword,etNewPassword,etConfirmPassword,
	 			etCurrentTransactionPin,etNewTransactionPin,etconfirmtransactionPIn;
	  
	 	Button btnOk,btnCancel;
	 	Context mContext;
	 	MD5Generator mD5Generator=new MD5Generator();
	  
	 	 
	 	public ChangeCredentialsDialog(Context context)
	 	{
	 		super(context);
	 		mContext=context;
	 		 
	 		requestWindowFeature(Window.FEATURE_NO_TITLE) ;
	 		setContentView(com.distributor.R.layout.reset_all_pin);
	 		etCurrentPassword=(EditText)findViewById(R.id.etCurrentpassword_all);
	 		etNewPassword=(EditText)findViewById(R.id.etNewPassword_all);
	 		etConfirmPassword=(EditText)findViewById(R.id.etConfirmNewPassword_all);
	 		
	 		etCurrentTransactionPin=(EditText)findViewById(R.id.etCurrentTransactionPIN_all);
	 		etNewTransactionPin=(EditText)findViewById(R.id.etNewtransactionPIN_all);
	 		etconfirmtransactionPIn=(EditText)findViewById(R.id.etConfirmTransactionPIN_all);

	 		btnOk=(Button)findViewById(R.id.btn_ok);
	 		btnCancel=(Button)findViewById(R.id.btn_Cancel);
	 		
	 		btnOk.setOnClickListener(this);
	 		btnCancel.setOnClickListener(this); 
	 				
	 	}
	 	
	 	public void onClick(View v) 
	 	{	  
	 	    if (v == btnOk)
	 		{	
	 	    	if(validateinput())
	 	    	{
	 	    		//Toast.makeText(mContext, "Success",Toast.LENGTH_SHORT).show();
	 	    		pd=ProgressDialog.show(mContext,    
	 						 null,"Please Wait..." , true);
	    			 	pd.setContentView(R.layout.progress);
	 	    		new Thread(ChangePin).start();
	 	    	}
	 	    	 
	 		}
	 	    else if(v==btnCancel)
	 		{
	 			dismiss();
	 		}
	 	}
	 	Runnable ChangePin=new Runnable()
	 	{
	 		
	 		public void run() 
	 		{
	 			try
	 			{ 		
	 				
	 				final String newMobilePassword=mD5Generator.MD5(etNewPassword.getText().toString());
	 				final String newTransactionPin=mD5Generator.MD5(etNewTransactionPin.getText().toString());
	 				
	 				
	 					HttpClient httpclient = new DefaultHttpClient();
	 					HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/distributorapp.php");
	 					
	                    String checksum=mD5Generator.MD5(mD5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+newMobilePassword+"|"+newTransactionPin+"|"+AppData.getUserInfo().getpublickey()));
	                    System.out.println("Check Sum:"+checksum);
	                      
	                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	                      
	 				        nameValuePairs.add(new BasicNameValuePair("function", "MobileChangePassword"));
	 				        nameValuePairs.add(new BasicNameValuePair("LoginId", AppData.getUserInfo().getLoginID()));
	 				        nameValuePairs.add(new BasicNameValuePair("MobilePassword",newMobilePassword));
	 				        nameValuePairs.add(new BasicNameValuePair("TransactionPassword",newTransactionPin));
	 				        nameValuePairs.add(new BasicNameValuePair("Checksum",checksum));
	 				        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	 				        ResponseHandler<String> responseHandler = new BasicResponseHandler();
	 				        String response = httpclient.execute(httppost,responseHandler);
	 				        System.out.println("Response:"+response);
	 				        
	 				        final JSONObject jsonObject=new JSONObject(response);
	                         if(jsonObject.getString("ResponseCode").equals("000"))
	                         {
	                         	 handler.post(new Runnable() 
	                         	 {
	 								public void run() 
	 								{
	 									try
	 									{
		 									
		 									pd.dismiss();
		 									Toast.makeText(mContext, "Credentials changed Successfully",Toast.LENGTH_SHORT).show();
		 									AppData.getUserInfo().setLoginPin(newMobilePassword);
		 									AppData.getUserInfo().setTransactionPassword(newTransactionPin);
		 									dismiss();
		 									startActivity(new Intent(ActivityLogin.this,TabMain.class));
											finish();
	//	 									pd=ProgressDialog.show(mContext, null, "Please Wait..",true);
	//	 									pd.setContentView(R.layout.progress);
	//	 									new Thread(getProducts).start();
	 									}
	 									catch(final Exception e )
	 									{
	 										handler.post(new Runnable() 
	 			 	                       	 {
	 			 									public void run() 
	 			 									{
	 			 										pd.dismiss();
	 			 										dismiss();
	 			 										Toast.makeText(mContext, e.getMessage(),Toast.LENGTH_SHORT).show();
	 			 									}
	 			 							 });
	 									}
	 								 }
	 							});
	                         }
	                         else
	                         {
	                         	handler.post(new Runnable() 
	 	                       	 {
	 									public void run() 
	 									{
	 										pd.dismiss();
	 										dismiss();
	 										Toast.makeText(mContext, "Unsuccessful",Toast.LENGTH_SHORT).show();
	 									}
	 								});
	                         }
	 				
	 				
	 				
	 			}
	 			catch(final Exception e)
	 			{
	 				pd.dismiss();
	 				handler.post(new Runnable() 
	               	 {
	 						public void run() 
	 						{
	 							pd.dismiss();
	 							dismiss();
	 							Toast.makeText(mContext,""+e.getMessage() ,Toast.LENGTH_SHORT).show();
	 						}
	 				 });
	 				e.printStackTrace();
	 			}
	 			
	 		}
	 	};
	 	 
	 	private boolean validateinput()
	 	{
	 		 boolean flag=false;
	 		
	 		 if(etCurrentPassword.getText().toString().trim().length()==0)
	     	 {
	     		
	 			 Toast.makeText(mContext, "Please Enter Current Password",Toast.LENGTH_SHORT).show();
	 			 return false;
	     	 }
	 		 else
	 		 {
	 			 if(etCurrentPassword.getText().length()==6)
	     		 {
	 				 flag=true;
	     		 }
	 			 else
	 			 {
	     			 Toast.makeText(mContext, "Current Password Must be of 6 digit",Toast.LENGTH_SHORT).show();
	     			 return false;
	 			 }
	 		 }
	 		 
	 		 
	 		 //----------------------------------
	 		 if(etNewPassword.getText().toString().trim().length()==0)
	     	 {
	     		
	 			 Toast.makeText(mContext, "Please Enter New Password",Toast.LENGTH_SHORT).show();
	 			 return false;
	     	 }
	 		 else
	 		 {
	 			 if(etNewPassword.getText().length()==6)
	     		 {
	 				 flag=true;
	     		 }
	 			 else
	 			 {
	     			 Toast.makeText(mContext, "New Password Must be of 6 digit",Toast.LENGTH_SHORT).show();
	     			 return false;
	 			 }
	 		 }
	 		 
	 		 
	 		 //------------------------------------------
	 		 if(etConfirmPassword.getText().toString().trim().length()==0)
	     	 {
	     		
	 			 Toast.makeText(mContext, "Please Enter Confirm Password",Toast.LENGTH_SHORT).show();
	 			 return false;
	     	 }
	 		 else
	 		 {
	 			 if(etConfirmPassword.getText().length()==6)
	     		 {
	 				 flag=true;
	     		 }
	 			 else
	 			 {
	     			 Toast.makeText(mContext, "Confirm Password Must be of 6 digit",Toast.LENGTH_SHORT).show();
	     			 return false;
	 			 }
	 		 }
	     	 
	 		 try {
				if(AppData.getUserInfo().getLoginPin().equals(md5Generator.MD5(etCurrentPassword.getText().toString())))
				 {
					 System.out.println("User Pin:"+AppData.getUserInfo().getLoginPin()+
							 "\nPIN:"+etCurrentPassword.getText().toString());
					 
					 flag=true;
				 }
				 else
				 {
					 Toast.makeText(mContext, "Current Password is not same", Toast.LENGTH_SHORT).show();
					 return false;
				 }
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	 		 
	 		 if(etNewPassword.getText().toString().equals(etConfirmPassword.getText().toString()))
	 		 {
	 			 flag=true;
	 		 }
	 		 else
	 		 {
	 			 Toast.makeText(mContext, "New  Password and Confirm Password is not same", Toast.LENGTH_SHORT).show();
	 			 return false;
	 		 }
	 		 
	 		 
	 		 
	 		//------------------------------------------------------------------------------------------------------------ 
	 		 
	 		 
	 		 
	 		 if(etCurrentTransactionPin.getText().toString().trim().length()==0)
	     	 {
	     		
	 			 Toast.makeText(mContext, "Please Enter Current Transaction PIn",Toast.LENGTH_SHORT).show();
	 			 return false;
	     	 }
	 		 else
	 		 {
	 			 if(etCurrentTransactionPin.getText().length()==4)
	     		 {
	 				 flag=true;
	     		 }
	 			 else
	 			 {
	     			 Toast.makeText(mContext, "Current Transaction Pin Must be of 4 digit",Toast.LENGTH_SHORT).show();
	     			 return false;
	 			 }
	 		 }
	 		 
	 		 
	 		 //----------------------------------
	 		 if(etNewTransactionPin.getText().toString().trim().length()==0)
	     	 {
	     		
	 			 Toast.makeText(mContext, "Please Enter New Transaction Pin",Toast.LENGTH_SHORT).show();
	 			 return false;
	     	 }
	 		 else
	 		 {
	 			 if(etNewTransactionPin.getText().length()==4)
	     		 {
	 				 flag=true;
	     		 }
	 			 else
	 			 {
	     			 Toast.makeText(mContext, "New Transaction Pin Must be of 4 digit",Toast.LENGTH_SHORT).show();
	     			 return false;
	 			 }
	 		 }
	 		 
	 		 
	 		 //------------------------------------------
	 		 if(etconfirmtransactionPIn.getText().toString().trim().length()==0)
	     	 {
	     		
	 			 Toast.makeText(mContext, "Please Enter Confirm Transaction Pin",Toast.LENGTH_SHORT).show();
	 			 return false;
	     	 }
	 		 else
	 		 {
	 			 if(etconfirmtransactionPIn.getText().length()==4)
	     		 {
	 				 flag=true;
	     		 }
	 			 else
	 			 {
	     			 Toast.makeText(mContext, "Confirm Transaction Pin  Must be of 4 digit",Toast.LENGTH_SHORT).show();
	     			 return false;
	 			 }
	 		 }
	     	 //convert it to MD5
	 		 try 
	 		 {
				if(AppData.getUserInfo().getTransactionPassword().equals(md5Generator.MD5(etCurrentTransactionPin.getText().toString())))
				 {
					 flag=true;
				 }
				 else
				 {
					 Toast.makeText(mContext, "Current Transaction Pin is not same", Toast.LENGTH_SHORT).show();
					 return false;
				 }
			} 
	 		 catch (NoSuchAlgorithmException e) 
	 		 {
				// TODO Auto-generated catch block
				e.printStackTrace();
			 } 
	 		 catch (UnsupportedEncodingException e) 
	 		 {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	 		 
	 		 if(etNewTransactionPin.getText().toString().equals(etconfirmtransactionPIn.getText().toString()))
	 		 {
	 			 flag=true;
	 		 }
	 		 else
	 		 {
	 			 Toast.makeText(mContext, "New  Transaction Pin and Confirm Transaction Pin is not same", Toast.LENGTH_SHORT).show();
	 			 return false;
	 		 }
	 		  
	 		 
	 		 if(flag==true)
	 		 {
	 			 return true;
	 		 }
	 		 else
	 			 return false;
	 		 
	 	}
	 	
	 }	
}